/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Block;

import DAO.AccountDAO;
import DAO.ConnectDatabase;
import Helper.AccountHelper;
import common.Constant;
import common.TabPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import org.json.JSONObject;

/**
 *
 * @author KIENLT
 */
public class MainForm extends javax.swing.JFrame {

    private Timer time;
    Login login = null;
    String strAccountName;
    private boolean close = true;
    Socket mSock;

    /**
     * Creates new form MainForm
     */
    public MainForm() {
        
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        //
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                int confirm = JOptionPane.showConfirmDialog(MainForm.this, "Exit?", "Message", JOptionPane.YES_NO_OPTION);
                if(confirm == JOptionPane.YES_OPTION)
                {
                    System.exit(0);
                }else{}
            }
        });
        initComponents();
        checkConnectDatabase();
        checkLogin();
        loadTime();
        changeLanguage();
        loadContent();
        pack();
    }

    private void alertToServer() {
        if (mSock == null) {
            try {
                // TODO add your handling code here:
                mSock = new Socket("192.168.1.108", 9999);
                OutputStream os = mSock.getOutputStream();
                JSONObject json = new JSONObject();
                json.put("from", lblFullName.getText());
                json.put("command", "alert");
                PrintWriter pw = new PrintWriter(os, true);
                pw.println(json.toString());
            } catch (UnknownHostException ex) {
                Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this, "khong connect dc server");
            } catch (IOException ex) {
                Logger.getLogger(ChatForm.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this, "khong connect dc server");
            }
        }
    }

    private void loadContent() {
        getFullName();
        ClassLoader cl = this.getClass().getClassLoader();
        tabMain.removeAll();
        
        
        if(login.getStrLevel().equals("1")){
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("createWeek"), new ImageIcon(cl.getResource("Images\\img_x48\\gnome_mail_mark_unread.png")), new Weeks(), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("scheduler"), new ImageIcon(cl.getResource("Images\\img_x48\\calendar-date-icone-6695-48.png")), new Scheduler(login.getStrLevel()), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerDoctor"), new ImageIcon(cl.getResource("Images\\img_x48\\g221.png")), new GroupDoctors(login.getStrLevel()), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerDeparment"), new ImageIcon(cl.getResource("Images\\img_x48\\department-icone-5900-48.png")), new Department(), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerRooms"), new ImageIcon(cl.getResource("Images\\img_x48\\images2.png")), new Rooms(), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerEmail"), new ImageIcon(cl.getResource("Images\\img_x48\\gnome_mail_mark_unread.png")), new Email(), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerPatient"), new ImageIcon(cl.getResource("Images\\img_x48\\b121.png")), new Patient(), tabMain);
        }
        if(login.getStrLevel().equals("2")){
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("scheduler"), new ImageIcon(cl.getResource("Images\\img_x48\\calendar-date-icone-6695-48.png")), new Scheduler(login.getStrLevel()), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerEmail"), new ImageIcon(cl.getResource("Images\\img_x48\\gnome_mail_mark_unread.png")), new Email(), tabMain);
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerPatient"), new ImageIcon(cl.getResource("Images\\img_x48\\b121.png")), new Patient(), tabMain);
            
        }
        if(login.getStrLevel().equals("3")){
            tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("managerEmail"), new ImageIcon(cl.getResource("Images\\img_x48\\gnome_mail_mark_unread.png")), new Email(), tabMain);
        }
//        tabMain = TabPanel.AddTabPanel(Constant.getBundle().getString("createAccount"), new ImageIcon(cl.getResource("Images\\img_x48\\create_account.png")), new ChatForm(login.getStrUserID()), tabMain);
    }

    private void changeLanguage() {
        if (Constant.getLanguage() == 0) {
            Constant.initBundle();
            getLanguage();
        } else {
            Constant.initBundle();
            getLanguage();
        }

    }

    private void getLanguage() {
        mnHelp.setText(Constant.getBundle().getString("help"));
        mnAbout.setText(Constant.getBundle().getString("about"));
        mnAccount.setText(Constant.getBundle().getString("account"));
        mnAccountInfor.setText(Constant.getBundle().getString("accountInfor"));
        mnChangePass.setText(Constant.getBundle().getString("changePass"));
        mnSignOut.setText(Constant.getBundle().getString("signout"));
        mnExit.setText(Constant.getBundle().getString("exit"));
        mnLanguage.setText(Constant.getBundle().getString("language"));
        mnEN.setText(Constant.getBundle().getString("en"));
        mnVN.setText(Constant.getBundle().getString("vn"));
    }

    private void checkLogin() {
        if (lblFullName.getText().equals("")) {
            login = new Login(this, true);
            login.setVisible(true);
        }
    }

    private void loadTime() {
        time = new Timer(1000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Calendar c = Calendar.getInstance();
                String strS = "";
                String strM = "";
                int h = c.get(Calendar.HOUR_OF_DAY);

                int m = c.get(Calendar.MINUTE);
                if (m < 10) {
                    strM = "0" + m;
                } else {
                    strM = "" + m;
                }

                int s = c.get(Calendar.SECOND);
                if (s < 10) {
                    strS = "0" + s;
                } else {
                    strS = "" + s;
                }

                lblClock.setText(h + " : " + strM + " : " + strS);
            }
        });
        time.start();
    }

    private void checkConnectDatabase() {
        if (ConnectDatabase.ConnectionDatabase() == null) {
            ConfigConnection c = new ConfigConnection(this, true);
            c.setVisible(true);
        }
    }

    private void getFullName() {
        AccountHelper accountData = new AccountHelper();
        accountData.setAccountId(login.getStrUserID());
        Connection cnn = ConnectDatabase.ConnectionDatabase();
        try {
            ResultSet rs = AccountDAO.FillOne(cnn, accountData);
            if (rs.next()) {
                lblFullName.setText(rs.getString("FullName"));
            }
        } catch (Exception ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void reload(Vector vtData) {
        lblFullName.setText((vtData.elementAt(0)).toString());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        lblTime = new javax.swing.JLabel();
        lblHi = new javax.swing.JLabel();
        lblFullName = new java.awt.Label();
        lblClock = new java.awt.Label();
        jLabel1 = new javax.swing.JLabel();
        tabMain = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        mnAccount = new javax.swing.JMenu();
        mnAccountInfor = new javax.swing.JMenuItem();
        mnChangePass = new javax.swing.JMenuItem();
        mnSignOut = new javax.swing.JMenuItem();
        mnExit = new javax.swing.JMenuItem();
        mnLanguage = new javax.swing.JMenu();
        mnEN = new javax.swing.JCheckBoxMenuItem();
        mnVN = new javax.swing.JCheckBoxMenuItem();
        mnHelp = new javax.swing.JMenu();
        mnAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Manger Remedy Scheduler");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jPanel1.setEnabled(false);
        jPanel1.setPreferredSize(new java.awt.Dimension(1000, 25));

        lblTime.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x32/clock-icone-9540-32.png"))); // NOI18N

        lblHi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x32/doctor.png"))); // NOI18N
        lblHi.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        lblFullName.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N

        lblClock.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 548, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lblHi, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblFullName, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblTime, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblClock, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(lblTime, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblHi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblFullName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblClock, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tabMain.setTabPlacement(javax.swing.JTabbedPane.LEFT);
        tabMain.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                tabMainStateChanged(evt);
            }
        });

        mnAccount.setText("Account");

        mnAccountInfor.setText("Account Information");
        mnAccountInfor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnAccountInforActionPerformed(evt);
            }
        });
        mnAccount.add(mnAccountInfor);

        mnChangePass.setText("Change Password");
        mnChangePass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnChangePassActionPerformed(evt);
            }
        });
        mnAccount.add(mnChangePass);

        mnSignOut.setText("Sign Out");
        mnSignOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnSignOutActionPerformed(evt);
            }
        });
        mnAccount.add(mnSignOut);

        mnExit.setText("Exit");
        mnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnExitActionPerformed(evt);
            }
        });
        mnAccount.add(mnExit);

        jMenuBar1.add(mnAccount);

        mnLanguage.setText("Language");

        buttonGroup1.add(mnEN);
        mnEN.setSelected(true);
        mnEN.setText("English");
        mnEN.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnENActionPerformed(evt);
            }
        });
        mnLanguage.add(mnEN);

        buttonGroup1.add(mnVN);
        mnVN.setText("Vietnamese");
        mnVN.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnVNActionPerformed(evt);
            }
        });
        mnLanguage.add(mnVN);

        jMenuBar1.add(mnLanguage);

        mnHelp.setText("Help");

        mnAbout.setText("About");
        mnHelp.add(mnAbout);

        jMenuBar1.add(mnHelp);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 960, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addComponent(tabMain, javax.swing.GroupLayout.PREFERRED_SIZE, 980, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabMain, javax.swing.GroupLayout.DEFAULT_SIZE, 569, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mnVNActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnVNActionPerformed
        // TODO add your handling code here:
        Constant.setLanguage(1);
        changeLanguage();
        loadContent();
    }//GEN-LAST:event_mnVNActionPerformed

    private void mnENActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnENActionPerformed
        // TODO add your handling code here:
        Constant.setLanguage(0);
        changeLanguage();
        loadContent();
    }//GEN-LAST:event_mnENActionPerformed

    private void mnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnExitActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_mnExitActionPerformed

    private void mnSignOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnSignOutActionPerformed
        // TODO add your handling code here:
        login = new Login(this, rootPaneCheckingEnabled);
        login.setVisible(true);
    }//GEN-LAST:event_mnSignOutActionPerformed

    private void tabMainStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tabMainStateChanged
        // TODO add your handling code here:
//        int iSelected = tabMain.getSelectedIndex();
//        if (iSelected == 6) {
//            alertToServer();
//            if (mSock != null) {
//                if (((ChatForm) tabMain.getComponentAt(iSelected)).getS() == null) {
//                    ((ChatForm) tabMain.getComponentAt(iSelected)).setS(mSock);
//                }
//            }
//        }
    }//GEN-LAST:event_tabMainStateChanged

    private void mnAccountInforActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnAccountInforActionPerformed
        // TODO add your handling code here:
        AccountInformation accountInfor = new AccountInformation(this, true, login.getStrUserID());
        accountInfor.setVisible(true);
    }//GEN-LAST:event_mnAccountInforActionPerformed

    private void mnChangePassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnChangePassActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_mnChangePassActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//        try {
            /*
         * Set the Nimbus look and feel
         */


        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainForm().setVisible(true);
            }
        });
//        } catch (ClassNotFoundException ex) {
//            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (UnsupportedLookAndFeelException ex) {
//            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private java.awt.Label lblClock;
    private java.awt.Label lblFullName;
    private javax.swing.JLabel lblHi;
    private javax.swing.JLabel lblTime;
    private javax.swing.JMenuItem mnAbout;
    private javax.swing.JMenu mnAccount;
    private javax.swing.JMenuItem mnAccountInfor;
    private javax.swing.JMenuItem mnChangePass;
    private javax.swing.JCheckBoxMenuItem mnEN;
    private javax.swing.JMenuItem mnExit;
    private javax.swing.JMenu mnHelp;
    private javax.swing.JMenu mnLanguage;
    private javax.swing.JMenuItem mnSignOut;
    private javax.swing.JCheckBoxMenuItem mnVN;
    private javax.swing.JTabbedPane tabMain;
    // End of variables declaration//GEN-END:variables
}
